<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2023 yoncron All rights reserved.
// +----------------------------------------------------------------------
// | Author: yoncron <yoncron@163.com>
// +----------------------------------------------------------------------

namespace app\model;


use app\common\Page;
use think\Model;

class ModelBase extends Model
{
    public function __construct(array $data = []){
        //echo "ModelBase __construct\r\n";
        parent::__construct($data);
    }

    public function __destruct(){
        //echo "ModelBase __destruct\r\n";
    }

    public function checkFieldExistence($field,$val,$pk=0){
        if($this->hav_deleted_column){
            $res = $this->where([[$field,'=',$val],[$this->pk,'<>',$pk],['deleted','=',0]])->find();
            return $res?1:0;
        }
        else{
            $res = $this->where([[$field,'=',$val],[$this->pk,'<>',$pk]])->find();
            return $res?1:0;
        }

    }

    public function lst($where=[],$order='sort asc'){
        $count = $this->where($where)->count();
        $page = new Page($count,input('limit',$count),input('page',1));
        $lst = $this->where($where)->limit($page->firstRow , $page->listRows)->order($order)->select();
        $res['code'] = 0;
        $res['list'] = $lst;
        $res['count'] = $count;
        $res['totalPages'] = $page->totalPages;
        return $res;
    }

    public function add($data=[]){
        if(empty($data)){
            return error(1,'请求数据不能为空');
        }
        foreach($this->checkField as $field){
            if($this->checkFieldExistence($field['column'],$data[$field['column']])){
                return error(1,$field['name'].'"'.$data[$field['column']].'"已存在');
            }
        }
        $res = $this->insertGetId($data);
        return $res;
    }

    public function edt($data=[]){
        if(empty($data)){
            return error(1,'请求数据不能为空');
        }
        foreach($this->checkField as $field){
            if(isset($data[$field['column']])){
                if($this->checkFieldExistence($field['column'],$data[$field['column']],$data[$this->pk])){
                    return error(1,$field['name'].'"'.$data[$field['column']].'"已存在');
                }
            }
        }
        $res = $this->update($data);
        return $res;
    }

    public function del(){
        if(input($this->pk,null)===null){
            return error(1,$this->pk_name.'不能为空');
        }
        $_id = input($this->pk);
        $where[]=[$this->pk,'in',strval($_id)];
        if($this->hav_deleted_column){
            return $this->where($where)->update(['del_time'=>time(),'deleted'=>1]);
        }
        else{
            return $this->where($where)->delete();
        }
    }
}